﻿using System;
using System.Collections.Generic;
using System.Linq;
using behaviors.Controllers;
using FubuCore;
using FubuMVC.Core.Registration;
using FubuMVC.Core.Registration.Nodes;

namespace behaviors.Behaviors
{
    public class AppendFooterTextWhereAppropiate 
        : IConfigurationAction
    {
        private readonly Type behavior = typeof(FooterTextBehavior<>);

        public void Configure(BehaviorGraph graph)
        {
            graph
                .Actions()
                .Where(call => call.HasOutput)
                .Where(call => call.OutputType().IsConcreteTypeOf<IFooter>())
                .Each(call => AddBehaviorTo(call));
        }

        private void AddBehaviorTo(ActionCall call)
        {
            var closingType = call.OutputType();
            var closedBehavior = behavior.MakeGenericType(closingType);
            var wrapper = new Wrapper(closedBehavior);
            call.AddAfter(wrapper);
        }
    }
}